/*
 * @Author: zxc
 * @Date: 2020-11-18 13:51:06
 * @LastEditTime: 2020-11-18 14:26:51
 * @LastEditors: zxc
 * @Description:四数之和
 */
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function (nums, target) {
  nums.sort((a, b) => a - b)
  const res = [],
    len = nums.length
  for (var i = 0; i < len - 3; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) continue
    if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break
    if (nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 3] < target) {
      continue
    }

    for (var j = i + 1; j < len - 2; j++) {
      if (j - i > 1 && nums[j] === nums[j - 1]) continue
      if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break
      if (nums[i] + nums[j] + nums[len - 1] + nums[len - 2] < target) continue
      let L = j + 1
      let R = len - 1
      while (L < R) {
        let temp = nums[i] + nums[j] + nums[L] + nums[R]
        if (temp === target) {
          res.push([nums[i], nums[j], nums[L], nums[R]])
          while (L < R && nums[L] === nums[L + 1]) L++
          while (L < R && nums[R] === nums[R - 1]) R--
          L++
          R--
        } else if (temp > target) R--
        else L++
      }
    }
  }
  return res
}
